<template>
	<view>
		<template v-if="showSkeleton">
			<view class="skeleton-box" v-for="(item,index) in skeletonRectLists" :key="index"
				:style="'border-radius: 10rpx;width: '+item.width+'px; height: '+item.height+'px;position: absolute; left:' +(item.left - selectorLeft)+'px; top:'+(item.top-selectorTop)+ 'px'">
			</view>

		</template>
		<view :class="{'opacity-default':showSkeleton}">
			<slot :skeletonData='skeletonData'></slot>
		</view>

	</view>
</template>

<script>
	export default {
		name: "skeleton",
		data() {
			return {
				skeletonRectLists: [], //占位数据
				showSkeleton: true, //显示占位
				selectorTop: 0,
				selectorLeft: 0,

			};
		},
		props: {
			// class name
			selector: {
				type: String,
				default: 'selector'
			},
			// defaultPadding: {
			// 	type: Number,
			// 	default: 0
			// },
			// 真实数据
			dataList: {
				type: Object || Array,
				default: null
			},
			// 默认占位数据
			dataDefault: {
				type: Array,
				default: []
			}
		},
		computed: {
			skeletonData() {
				console.log('this.dataList', this.dataList);
				if (this.dataList) {
					setTimeout(() => {
						this.showSkeleton = false;
					})
					return this.dataList
				}
				this.showSkeleton = true;
				return this.dataDefault
			}
		},
		mounted() {
			let _this = this;
			this.$nextTick(() => {
				wx.createSelectorQuery().selectAll(`.${this.selector}`)
					.boundingClientRect().exec(
						function(res) {
							_this.selectorTop = res[0][0].top || 0
							_this.selectorLeft = res[0][0].left || 0
						});

				wx.createSelectorQuery().selectAll(`.${this.selector} >>> .${this.selector}-rect`)
					.boundingClientRect().exec(
						function(res) {
							_this.skeletonRectLists = res[0]
						});
			})
		},

	}
</script>

<style scoped lang="scss">
	.skeleton-box {
		// background-color: #d6dae4;
		z-index: 99;
		// background: linear-gradient(90deg, #d6dae4 50%, #fff 50%);
		background-image: linear-gradient(-60deg, #f1f2f4 25%, #e6e6e6 37%, #f1f2f4 50%);
		// background-size: 100% 20%;
		background-size: 400% 100%;
		// background-position: 100% 50%;
		/* 渐变区域的大小 */
		animation: skeleton-loading 1.4s ease infinite;
	}

	.opacity-default {
		opacity: 0;
	}

	@keyframes skeleton-loading {
		0% {
			background-position: 100% 50%;
		}

		100% {
			background-position: 0 50%;
		}
	}
</style>
